package com.controller;

import com.pojo.Address;
import com.pojo.Result;
import com.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//跨域
@CrossOrigin
@RestController
@RequestMapping("/address")
public class AddressController {

    //注入addressService
    @Autowired
    private AddressService addressService;

    //添加
    @PostMapping
    public Result add(@RequestBody Address address){
        boolean flag = addressService.add(address);
        Result result = new Result();
        if(flag){
            result.setCode(200);
            result.setMsg("添加成功");
        }else{
            result.setCode(500);
            result.setMsg("添加失败");
        }

        return result;
    }

    //查询这个用户所有地址
    @GetMapping("/{uId}")
    public Result findAllByUid(@PathVariable Integer uId){
        List<Address> list = addressService.findAllByUid(uId);
        Result result = new Result();

        if (list != null){
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(list);
        }else {
            result.setCode(500);
            result.setMsg("查询失败");
            //result.setData(list);
        }

        return result;

    }
    //修改单个地址
    @PutMapping
    public Result updateanaddress(@RequestBody Address address){
        boolean flag = addressService.update(address);
        Result result = new Result();
        if(flag){
            result.setCode(200);
            result.setMsg("修改成功");
        }else{
            result.setCode(500);
            result.setMsg("修改失败");
        }

        return result;
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = addressService.delete(id);
        Result result = new Result();
        if(flag){
            result.setCode(200);
            result.setMsg("删除成功");
        }else{
            result.setCode(500);
            result.setMsg("删除失败");
        }

        return result;
    }

    //修改默认地址
    @PutMapping("/{uid}/{id}")
    public Result updatedefault(@PathVariable Integer uid,@PathVariable Integer id){
        boolean flag =addressService.updatedefault(uid,id);
        Result result = new Result();
        if(flag){
            result.setCode(200);
            result.setMsg("修改成功");
        }else{
            result.setCode(500);
            result.setMsg("修改失败");
        }

        return result;

    }
    //修改默认地址为不默认
    @PutMapping("/{id}")
    public Result updateondefault(@PathVariable Integer id){
        boolean flag =addressService.updateondefault(id);
        Result result = new Result();
        if(flag){
            result.setCode(200);
            result.setMsg("修改成功");
        }else{
            result.setCode(500);
            result.setMsg("修改失败");
        }

        return result;

    }
}